#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <errno.h>

#define PORT 8888          // 服务器端口
#define MAX_EVENTS 100     // epoll 最大事件数
#define BUFFER_SIZE 1024   // 缓冲区大小

int main() {
    int server_fd, client_fd;
    struct sockaddr_in server_addr, client_addr;
    char buffer[BUFFER_SIZE];
    socklen_t addr_len;

    // 创建服务器套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址结构
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);

    // 绑定服务器地址和端口
    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 监听端口
    if (listen(server_fd, 5) < 0) {
        perror("listen failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }
    printf("服务器启动，监听端口 %d\n", PORT);

    // 创建 epoll 实例
    int epoll_fd = epoll_create1(0);
    if (epoll_fd == -1) {
        perror("epoll_create1 failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 添加服务器套接字到 epoll
    struct epoll_event event, events[MAX_EVENTS];
    event.events = EPOLLIN; // 监听可读事件
    event.data.fd = server_fd;
    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, server_fd, &event) == -1) {
        perror("epoll_ctl failed");
        close(server_fd);
        close(epoll_fd);
        exit(EXIT_FAILURE);
    }

    while (1) {
        // 等待事件触发
        int event_count = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
        if (event_count == -1) {
            perror("epoll_wait failed");
            continue;
        }

        for (int i = 0; i < event_count; i++) {
            int event_fd = events[i].data.fd;

            // 检查是否有新的连接
            if (event_fd == server_fd) {
                addr_len = sizeof(client_addr);
                client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addr_len);
                if (client_fd < 0) {
                    perror("accept failed");
                    continue;
                }

                printf("新连接: 套接字 %d, IP: %s, 端口: %d\n",
                       client_fd, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

                // 将新连接添加到 epoll
                event.events = EPOLLIN; // 只监听读事件
                event.data.fd = client_fd;
                if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_fd, &event) == -1) {
                    perror("epoll_ctl add client failed");
                    close(client_fd);
                }
            } else if (events[i].events & EPOLLIN) {
                // 处理客户端消息
                int bytes_read = read(event_fd, buffer, BUFFER_SIZE);
                if (bytes_read == 0) {
                    // 客户端断开连接
                    addr_len = sizeof(client_addr);
                    getpeername(event_fd, (struct sockaddr *)&client_addr, &addr_len);
                    printf("客户端断开: IP: %s, 端口: %d\n",
                           inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
                    close(event_fd);
                    epoll_ctl(epoll_fd, EPOLL_CTL_DEL, event_fd, NULL);
                } else {
                    // 处理收到的数据
                    buffer[bytes_read] = '\0';
                    printf("来自套接字 %d 的消息: %s\n", event_fd, buffer);

                    // 回显消息给客户端
                    if (send(event_fd, buffer, bytes_read, 0) < 0) {
                        perror("send error");
                        close(event_fd);
                        epoll_ctl(epoll_fd, EPOLL_CTL_DEL, event_fd, NULL);
                    }
                }
            }
        }
    }

    close(server_fd);
    close(epoll_fd);
    return 0;
}
